/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IFSv2.Forms;

import IFSv2.Connection.DBConnection;
import IFSv2.Forms.Main.MainToolBar;
import IFSv2.Operations.clsMain;
import java.awt.event.KeyEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.JOptionPane;

public class frmAPmain extends javax.swing.JPanel{

    private final String REFCOLUMN = "VoucherNbr";
    private final String PRIMARYKEY = "BatNbr";
    private final String TABLENAME = "vaphdr";
    
    private javax.swing.table.DefaultTableModel table;
    private String selectedID;
    private String selectedPrimaryID;
    private String _sqlCmd;
    
    private int numOfCols;
    
    
    public frmAPmain() {
        initComponents();
        getTableColumns();
    }

    /*
     * This will be called by the main program to update the buttons.
     * DEFAULT - Only the New button is activated
     */
    public void reloadToolBar(){
        MainToolBar.enableButtons("DEFAULT");
    }
    
    /*
     * this will be the listener of the form from the toolbar
     */
    public void buttonClicked(final String btn){
        if("btnNew".equals(btn)){
            clsMain.openTab("Voucher Entry", new frmAPhdr());
        }
    }
        
    private void getTableColumns(){

        table = (javax.swing.table.DefaultTableModel) jTable1.getModel();
        _sqlCmd = "SELECT * FROM " + TABLENAME;
        try {
            ResultSetMetaData rsmdTableCol;
            try (ResultSet rsTableCol = DBConnection.getActiveConnection().createStatement().executeQuery(_sqlCmd + " LIMIT 1")) {
                rsmdTableCol = rsTableCol.getMetaData();
            }
            numOfCols = rsmdTableCol.getColumnCount();
            for(int i=1; i< numOfCols; i++){
                table.addColumn(rsmdTableCol.getColumnName(i));
                columnCombo.addItem(rsmdTableCol.getColumnName(i));
            }
            columnCombo.setSelectedItem(REFCOLUMN);
        } catch (SQLException ex) {}
        
    }
    
    private void updateTable(String searchText){
        jTable1.requestFocus();
        String _sqlCmd;
        if(searchText != null)
            _sqlCmd = this._sqlCmd + " WHERE "+columnCombo.getSelectedItem()+" LIKE ?";
        else 
            _sqlCmd = this._sqlCmd;
            
        jTable1.setSurrendersFocusOnKeystroke(true);
        table = (javax.swing.table.DefaultTableModel) jTable1.getModel();  
        
        try{
            table.setRowCount(0);
        }catch(Exception e){}
        
        try {
            PreparedStatement ps = DBConnection.getActiveConnection().prepareStatement(_sqlCmd);
            ps.setString(1, '%'+searchText+'%');
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                Object[] data = new Object[numOfCols];
                for(int i=0; i<data.length; i++){
                    data[i] = rs.getObject(i+1);
                }
                table.addRow(data);
            }
            table.fireTableDataChanged();
        } catch (SQLException ex) {} 
    }

    private void getCurrentRow(){
        selectedID = table.getValueAt(jTable1.getSelectedRow(), table.findColumn(REFCOLUMN)).toString();
        selectedPrimaryID = table.getValueAt(jTable1.getSelectedRow(), table.findColumn(PRIMARYKEY)).toString();
        clsMain.openTab("Voucher:"+selectedID, new frmAPhdr(selectedPrimaryID));
    }
    
    private void getSearchTFValue() {
        String searchText;
        
        if (searchTbx.getText().isEmpty()){
            final int result = JOptionPane.showConfirmDialog(null,"You did not provide a parameter. This may take a while. \nDo you want to Continue?","",JOptionPane.YES_NO_OPTION);
            if(result == JOptionPane.YES_OPTION){
                updateTable(searchTbx.getText());
            }
        }else{
           searchText = searchTbx.getText().trim();
           updateTable(searchText);
        }
    }
    
   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        columnCombo = new javax.swing.JComboBox();
        searchTbx = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();

        setBackground(new java.awt.Color(255, 255, 255));

        searchTbx.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                searchTbxKeyPressed(evt);
            }
        });

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }

        ){
            public boolean isCellEditable(int row, int column){
                return false;
            }

        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("No. Of Posted/Unposted Vouchers per Day"));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 403, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 175, Short.MAX_VALUE)
        );

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Company Expenditure per Day"));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 403, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 175, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(columnCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchTbx))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 924, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(columnCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchTbx, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void searchTbxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTbxKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            getSearchTFValue();
        }
    }//GEN-LAST:event_searchTbxKeyPressed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (evt.getClickCount() == 2) {
            getCurrentRow();
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            getCurrentRow();
        }
    }//GEN-LAST:event_jTable1KeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox columnCombo;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField searchTbx;
    // End of variables declaration//GEN-END:variables
}
